package com.shuziren.controller.human;


import com.shuziren.entity.dto.PromptDTO;
import com.shuziren.entity.vo.MessageVo;
import com.shuziren.repostory.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;

import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Collection;
import java.util.Collections;
import java.util.List;


@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class CustomerServiceController {

    private final ChatClient serviceChatClient;

    private final ChatClient pmortCharclinet;

    private final ChatHistoryRepository chatHistoryRepository;

    private final ChatMemory chatMemory;

    /**
     * 客服服务
     * @param prompt
     * @return String
     */
    @PostMapping(value = "/service", produces = "text/html;charset=utf-8")
    public String service(@RequestBody @Validated PromptDTO prompt) {
        // 1.保存会话id
        chatHistoryRepository.save("service", prompt.getChatId());
        // 2.请求模型

        return serviceChatClient.prompt()
                .user(prompt.getPrompt())
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, prompt.getChatId()))
                .call()
                .content();
    }


    @PostMapping(value = "/pmort", produces = "text/html;charset=utf-8")
    public Flux<String> pmort(@RequestBody @Validated PromptDTO prompt){
        chatHistoryRepository.save("pmort", prompt.getChatId());

        return  serviceChatClient.prompt()
                .user(prompt.getPrompt())
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, prompt.getChatId()))
                .stream()
                .content();
    }

    @PostMapping(value = "/game", produces = "text/html;charset=utf-8")
    public Flux<String> game(@RequestBody @Validated PromptDTO prompt){
        chatHistoryRepository.save("pmort", prompt.getChatId());
        return  serviceChatClient.prompt()
                .user(prompt.getPrompt())
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, prompt.getChatId()))
                .stream()
                .content();
    }

    /**
     *  获取历史会话
     * @param type 会话类型
     * @param chatId 会话ID
     * @return 会话记录
     */
    @GetMapping("/{type}/{chatId}")
    public List<MessageVo> getChatHistroy(@PathVariable("type") String type
            , @PathVariable String chatId){
        List<Message> messages = chatMemory.get(chatId);
        Object o = new Object();
        if (messages == null){
            return List.of();
        }

        return messages.stream().map(MessageVo::new).toList();
    }

}
